package cn.edu.gzhu.workOrderManagement.service.impl;

import cn.edu.gzhu.workOrderManagement.enumeration.UserAuthorityEnum;
import cn.edu.gzhu.workOrderManagement.enumeration.WorkOrderProcessingStatusEnum;
import cn.edu.gzhu.workOrderManagement.mapper.ReminderMapper;
import cn.edu.gzhu.workOrderManagement.mapper.WorkOrderMapper;
import cn.edu.gzhu.workOrderManagement.pojo.dto.reminder.ReminderCreateDto;
import cn.edu.gzhu.workOrderManagement.pojo.dto.reminder.ReminderHistoryDto;
import cn.edu.gzhu.workOrderManagement.pojo.entity.Reminder;
import cn.edu.gzhu.workOrderManagement.pojo.entity.WorkOrder;
import cn.edu.gzhu.workOrderManagement.result.Result;
import cn.edu.gzhu.workOrderManagement.service.ReminderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

@Service
public class ReminderServiceImpl implements ReminderService {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    WorkOrderMapper workOrderMapper;
    @Autowired
    ReminderMapper reminderMapper;
    @Override
    /**
     * @param username
     * @param reminderCreateDto
     */
    public Boolean createReminder(String username, ReminderCreateDto reminderCreateDto) {
        String workOrderUuid = reminderCreateDto.getWorkOrderUuid();
        WorkOrder workOrder = workOrderMapper.selectOne(new QueryWrapper<WorkOrder>().eq("uuid", workOrderUuid));
        if (workOrder == null) {
            return false;
        }

        // 1️⃣ 构造 Reminder 对象
        LocalDateTime now = LocalDateTime.now().withNano(0);
        Reminder newReminder = Reminder.builder()
                .workOrderUuid(workOrderUuid)
                .posterUsername(username)
                .isRead(false)
                .createTime(now)
                .build();

        // 2️⃣ 根据权限等级和组织信息构造 Redis 键（key）
        UserAuthorityEnum authority = WorkOrderProcessingStatusEnum.getAuthorityEnum(workOrder);
        if (authority == null) {
            return false;
        }
        Integer targetLevel = authority.getAuthority();

        String channel;
        if (targetLevel == 2) {
            // 比如：总部商务
            channel = authority.name(); // 如 HEAD_BUSINESS
        } else if (targetLevel == 3) {
            // 比如：Suzhou:BRANCH_BUSINESS
            channel = workOrder.getBranchName() + ":" + authority.name();
        } else if (targetLevel == 4) {
            // 比如：Suzhou:7
            channel = workOrder.getBranchName() + ":" + workOrder.getTeamMember();
        } else {
            return false;
        }

        // 3️⃣ 使用组合的 key：channel + ":" + workOrderUuid
        String redisKey = channel + ":" + workOrderUuid;  // 组合键：新组织:1:c123

        // 4️⃣ 保存到 Redis（使用 SET 来替换已有的值）
        redisTemplate.opsForValue().set(redisKey, newReminder.toValue());  // 使用 SET 来替换已有的值

        // 5️⃣ 保存到 MySQL
        int insert = reminderMapper.insert(newReminder);
        if (insert != 1) {
            return false;
        }

        return true;
    }



    /**
     * @param reminderHistoryDto
     * @return
     */
    @Override
    public IPage getHistoryReminder(ReminderHistoryDto reminderHistoryDto) {
        Page<Reminder> reminderPage = new Page<>(reminderHistoryDto.getStartPage(), reminderHistoryDto.getPageSize());
        LambdaQueryWrapper<Reminder> queryWrapper = new LambdaQueryWrapper<Reminder>();
        if (reminderHistoryDto.getWorkOrderUuid() != null&& !reminderHistoryDto.getWorkOrderUuid().isEmpty()) {
            queryWrapper.eq(Reminder::getWorkOrderUuid, reminderHistoryDto.getWorkOrderUuid());
        }

        if (reminderHistoryDto.getPosterUsername() != null&& !reminderHistoryDto.getPosterUsername().isEmpty()) {
            queryWrapper.eq(Reminder::getPosterUsername, reminderHistoryDto.getPosterUsername());
        }
        if (reminderHistoryDto.getIsRead() != null) {
            queryWrapper.eq(Reminder::getIsRead, reminderHistoryDto.getIsRead());
        }
        queryWrapper.orderByDesc(Reminder::getCreateTime);
        IPage<Reminder> iPage = reminderMapper.selectPage(reminderPage, queryWrapper);
        return iPage;
    }

    @Override
    public Boolean readReminder(List<String> workOrderUuids, List<String> PosterUsernames, List<LocalDateTime> times) {
        LambdaUpdateWrapper<Reminder> reminderUpdateWrapper = new LambdaUpdateWrapper<>();
        reminderUpdateWrapper.in(Reminder::getWorkOrderUuid, workOrderUuids);
        reminderUpdateWrapper.in(Reminder::getPosterUsername, PosterUsernames);
        reminderUpdateWrapper.in(Reminder::getCreateTime, times);
        reminderUpdateWrapper.set(Reminder::getIsRead, true);
        reminderMapper.update(null,reminderUpdateWrapper);
        return true;

    }


}
